package com.aipartner.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;

/**
 * WebClient配置
 * 
 * @author AI伙伴团队
 * @since 2024-01-20
 */
@Configuration
public class WebClientConfig {
    
    @Bean
    public WebClient webClient() {
        HttpClient base = HttpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000)
                .responseTimeout(Duration.ofSeconds(120))
                .doOnConnected(conn ->
                        conn.addHandlerLast(new ReadTimeoutHandler(120))
                            .addHandlerLast(new WriteTimeoutHandler(120))
                );

        // 代理支持（如需走公司代理/科学上网，在环境变量配置 HTTP_PROXY/HTTPS_PROXY）
        String proxy = System.getenv("HTTPS_PROXY");
        if (proxy == null || proxy.isEmpty()) {
            proxy = System.getenv("HTTP_PROXY");
        }

        HttpClient httpClient = base;
        if (proxy != null && proxy.startsWith("http")) {
            try {
                java.net.URI uri = java.net.URI.create(proxy);
                String host = uri.getHost();
                int port = (uri.getPort() > 0 ? uri.getPort() : ("https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80));
                httpClient = base.proxy(spec -> spec.type(reactor.netty.transport.ProxyProvider.Proxy.HTTP)
                        .host(host).port(port));
            } catch (Exception ignored) {}
        }

        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(20 * 1024 * 1024)) // 20MB
                .build();
    }
}
